import { pwdlogin, getInfo } from '@/api/login'
const logout = () => { }
import { getToken, setToken, removeToken } from '@/utils/auth'
import { getStore } from '@/utils/store'

const user = {
  state: {
    token: getToken(),
    roles: [],
    permissions: [],
    userInfo: {},
    routes: [],
    sysType: "ship", // ship 船端 shore 岸端
    mmsi: "",
  },
  mutations: {
    SET_ROUTES: (state, routes) => {
      // state.routes = constantRoutes.concat(routes)
      state.routes = routes
    },
    SET_TOKEN: (state, token) => {
      state.token = token
    },
    SET_ROLES: (state, roles) => {
      state.roles = roles
    },
    SET_PERMISSIONS: (state, permissions) => {
      state.permissions = permissions
    },
    SET_USERINFO: (state, data) => {
      state.userInfo = data
    },
  },
  actions: {
    pwdLogin({ commit }, userInfo) {
      return new Promise((resolve, reject) => {
        pwdlogin(userInfo).then(({ data }) => {
          const token = `Bearer ${data.token}`
          setToken(token)
          commit('SET_TOKEN', data.token)
          commit('SET_USERINFO', data)
          resolve()
        }).catch(error => {
          reject(error)
        })
      })
    },
    // 获取用户信息
    GetInfo({ commit }) {
      const userName = getStore({
        name: "userName",
        type: 1
      })
      return new Promise((resolve, reject) => {
        getInfo(userName).then(({ data }) => {
          commit('SET_USERINFO', data)
          resolve(data)
        }).catch(error => {
          reject(error)
        })
      })
    },
    // 退出系统
    LogOutByApi({ commit, state }) {
      return new Promise((resolve, reject) => {
        logout(state.token).then(() => {
          commit('SET_TOKEN', '')
          commit('SET_ROLES', [])
          commit('SET_PERMISSIONS', [])
          removeToken()
          resolve()
        }).catch(error => {
          reject(error)
        })
      })
    },
    // 退出系统
    LogOut({ commit }) {
      return new Promise((resolve) => {
        commit('SET_TOKEN', '')
        commit('SET_ROLES', [])
        commit('SET_PERMISSIONS', [])
        removeToken()
        resolve()
      })
    },
    // 前端 登出
    FedLogOut({ commit }) {
      return new Promise(resolve => {
        commit('SET_TOKEN', '')
        removeToken()
        resolve()
      })
    },
  }
}

export default user
